#!/bin/bash

set -euo pipefail

# Created at http://ellenandpaulsnewstartup.com - we're hiring!

function fix_dir_stdin {
  sed -e "s!$DIR!/home/opam/app!g"
}

function fix_dir_stdout {
  sed -e "s!/home/opam/app!$DIR!g" | sed -e "s!/home/opam/.opam/.*/bin!$DIR/scripts!g"
}

# Replace any filenames with the in-container filenames (stdin)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
ARGS=${@}
ARGS=$(echo ${ARGS} | fix_dir_stdin)

MYUID=$(id -u)
DOCKERNAME="codabuilder-$MYUID"

NAME=$(docker ps -q --filter "name=$DOCKERNAME")

if [ -t 0 ] ;
then
  docker exec -it "${NAME}" ${ARGS} ;
else
  # Replace any in-container filenames with host filesnames (stdout + stderr)
  { cat <&0 | fix_dir_stdin | docker exec -i "${NAME}" ${ARGS} 2>&1 1>&3 3>&- | fix_dir_stdout; } 3>&1 1>&2 | fix_dir_stdout
fi
